import {Menu, MenuProps,} from 'antd'
import {Res} from "@/app/lib/resource";
import Link from "next/link";
import { useContext, } from "react";
import {ResourceContext} from "@/app/lib/ResourceContext";
import {usePathname} from "next/navigation";

const menuBarStyle: React.CSSProperties = {
  width:'100%',
  fontSize:13,
  fontFamily:"Helvetica Neue, Helvetica, Arial, sans-serif",
};

function loadMenus(nav:string,allResources:Res[]|undefined):Res[]|undefined{
  if(allResources == undefined || allResources.length == 0){
    return [];
  }
  let targetNav = allResources.find(r => r.route == nav);
  return targetNav == undefined ? [] : targetNav.children;
}
function toMenuItems(items:Res[]|undefined):MenuProps['items']{
  if(items == undefined || items .length == 0){
    return undefined;
  }
 return items.map((m:Res) => {
    return {label:getLabel(m),key:m.id,icon:m.icon,children:toMenuItems(m.children)}
  })
}
function getLabel(m:Res){
  if(m.route == undefined){
    return m.name;
  }
  return (<Link href={m.route}>{m.name}</Link>);
}

function findKeys(menus: Res[] | undefined, pathname: string, paths: string[]) {
  if(!menus || menus.length == 0){
    return false;
  }
  for(const r of menus){
    paths.push(r.id);
    if(r.route == pathname){
      return true;
    }
    let flag = false;
    if(r.children && r.children.length > 0){
      flag = findKeys(r.children,pathname,paths);
    }
    if(flag){
      return true;
    }
    paths.pop();
  }
  return false
}

function findSelectedKeys(menus: Res[] | undefined, pathname: string):string[] {
  let paths:string[] = [];
  findKeys(menus,pathname,paths);
  return paths;
}

// @ts-ignore
export default function MenuBar({nav}){
  const resources = useContext(ResourceContext);
  let menus = loadMenus(nav,resources.navs);
  const pathname = usePathname()
  return (
    <Menu
      style={menuBarStyle}
      mode="inline"
      inlineIndent={24}
      items={toMenuItems(menus)}
      theme={"light"}
      selectedKeys={findSelectedKeys(menus,pathname)}
    />
  );
}